package com.ruoyi.tuanzhang.service.impl;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.tuanzhang.domain.vo.DarenVideoDetailsDataDto;
import com.ruoyi.tuanzhang.domain.DarenBaseDo;
import com.ruoyi.tuanzhang.domain.DarenLiveDetailsDataDo;
import com.ruoyi.tuanzhang.domain.DarenVideoDetailsDataDo;
import com.ruoyi.tuanzhang.domain.ProductDataDo;
import com.ruoyi.tuanzhang.domain.excelDto.DarenBaseExcelDto;
import com.ruoyi.tuanzhang.domain.excelDto.DarenBaseSinExcelDto;
import com.ruoyi.tuanzhang.domain.excelDto.DarenDataListDto;
import com.ruoyi.tuanzhang.domain.excelDto.ProductListExcelDto;
import com.ruoyi.tuanzhang.mapper.*;
import com.ruoyi.tuanzhang.mapper.impl.*;
import com.ruoyi.tuanzhang.service.IExcelHandleService;
import com.ruoyi.tuanzhang.utils.ExcelUtils;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ExcelHandleServiceImpl implements IExcelHandleService {

    private static final Logger logger = LoggerFactory.getLogger(ExcelHandleServiceImpl.class);

    @Resource private DarenBaseMapper darenBaseMapper;

    @Resource private DarenVideoDetailsDataMapper darenVideoDetailsDataMapper;
    @Resource private DarenLiveDetailsDataMapper darenLiveDetailsDataMapper;

    @Resource private ProductDataMapper productDataMapper;

    @Value("${basePath}")
    private String basePath;


    /**
     * 生成没有没有乱七八糟信息的表格（查询达人视频、直播、带货信息的表格）
     *
     * */
    @Override
    public String generatorInitBaseDoExcel () {
        // 达人基本信息
        LambdaQueryWrapper<DarenBaseDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(DarenBaseDo::getUnionUid);
        wrapper.gt(DarenBaseDo::getFansNum, 15000);
        List<DarenBaseDo> darenBaseDos = darenBaseMapper.selectList(wrapper);
        List<DarenBaseExcelDto> darenBaseList = JSONArray.parseArray(
                JSONArray.toJSONString(darenBaseDos)
                , DarenBaseExcelDto.class);
        DarenDataListDto darenDataListDto = new DarenDataListDto();
        darenDataListDto.setDarenBaseExcelDtoList(darenBaseList);

        ExcelUtils.getMulSheetExcel(darenDataListDto, basePath);
        return "生成成功";
    }

    @Override
    public String generatorBaseDoExcel () {
        // 达人基本信息
        LambdaQueryWrapper<DarenBaseDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DarenBaseDo::getCanAdd, 1);
        wrapper.isNotNull(DarenBaseDo::getUnionUid);
        wrapper.isNull(DarenBaseDo::getOwner);
        List<DarenBaseDo> darenBaseDos = darenBaseMapper.selectList(wrapper);

        /**
         * 表格出来的时候过滤掉：
         1、视频加直播少于15的
         2、直播观看人数中位数不少于3000人
         3、视频观看人数中位数不少过5000人
         4、没有微信的
         */
        List<DarenBaseDo> darenBaseFitleList = new ArrayList<>();
        for (DarenBaseDo darenBaseDo : darenBaseDos) {
            // 过滤掉   1、视频 + 直播数   +  4、没有微信的
            Integer allLiveVideoNum = darenBaseDo.getAllVideoNum30d() + darenBaseDo.getAllLiveNum30d();
            if (allLiveVideoNum >= 15 && darenBaseDo.getFansNum() > 15000
                    && Objects.nonNull(darenBaseDo.getShowWechat()) && darenBaseDo.getShowWechat() == 1
                    && Objects.isNull(darenBaseDo.getWechat())) {

                /*  过滤3、视频观看人数  */
                LambdaQueryWrapper<DarenVideoDetailsDataDo> videoQueryWrapper = new LambdaQueryWrapper<>();
                videoQueryWrapper.eq(DarenVideoDetailsDataDo::getUid, darenBaseDo.getUnionUid());
                videoQueryWrapper.orderByAsc(DarenVideoDetailsDataDo::getPlayTimes);
                List<DarenVideoDetailsDataDo> darenVideoDetailsDataDoList = darenVideoDetailsDataMapper.selectList(videoQueryWrapper);
                if (darenVideoDetailsDataDoList.size() > 3) {
                    int videoNum =  darenVideoDetailsDataDoList.size() / 2;
                    Integer playTimesOne = darenVideoDetailsDataDoList.get(videoNum).getPlayTimes();
                    Integer playTimesTwo = darenVideoDetailsDataDoList.get(videoNum + 1).getPlayTimes();
                    Integer playTimes = (playTimesOne + playTimesTwo) / 2;
                    if (playTimes >= 10000) {
                        darenBaseFitleList.add(darenBaseDo);
                        continue;
                    }
                }
                if (darenBaseDo.getAllLiveNum30d() > 3) {
                    // 直播列表
                    /*  过滤2、直播观看人数  */
                    LambdaQueryWrapper<DarenLiveDetailsDataDo> liveQueryWrapper = new LambdaQueryWrapper<>();
                    liveQueryWrapper.eq(DarenLiveDetailsDataDo::getUid, darenBaseDo.getUnionUid());
                    List<DarenLiveDetailsDataDo> liveDetailsDataDoList = darenLiveDetailsDataMapper.selectList(liveQueryWrapper);
                    if (liveDetailsDataDoList.size() > 3) {
                        int liveNum =  liveDetailsDataDoList.size() / 2;
                        Integer viewersOne = liveDetailsDataDoList.get(liveNum).getViewer();
                        Integer viewersTwo = liveDetailsDataDoList.get(liveNum + 1).getViewer();
                        Integer viewers = (viewersOne + viewersTwo) / 2;
                        if (viewers > 3000) {
                            darenBaseFitleList.add(darenBaseDo);
                        }
                    }
                }
            }
        }
        if(darenBaseFitleList.size() > 0){
            // 最终过滤之后的标准
            List<DarenBaseExcelDto> darenBaseList = JSONArray.parseArray(
                    JSONArray.toJSONString(darenBaseFitleList)
                    , DarenBaseExcelDto.class);
            DarenDataListDto darenDataListDto = new DarenDataListDto();
            darenDataListDto.setDarenBaseExcelDtoList(darenBaseList);

            ExcelUtils.getMulSheetExcel(darenDataListDto, basePath);
            return "生成成功";
        } else {
            return "都不符合标准";
        }

    }

    @Override
    public String generatorExcel () {
        // 达人基本信息
        List<DarenBaseDo> darenBaseDos = darenBaseMapper.selectSingleExcelList(new DarenBaseDo());
        List<DarenBaseExcelDto> darenBaseList = JSONArray.parseArray(
                JSONArray.toJSONString(darenBaseDos)
                , DarenBaseExcelDto.class);
        DarenDataListDto darenDataListDto = new DarenDataListDto();
        darenDataListDto.setDarenBaseExcelDtoList(darenBaseList);
        List<String> uids = Lists.newArrayList();
        Map<String, String> map = MapUtil.newHashMap();
        if (!darenBaseList.isEmpty()) {
            for (DarenBaseExcelDto dto : darenBaseList) {
                uids.add(dto.getUnionUid());
                map.put(dto.getUnionUid(), dto.getNickname());
            }
            // 达人主页信息
            darenDataListDto.setDarenHomeExcelDtoList(DarenHomeMapperImpl.getSingleExcel(uids, map));
            darenDataListDto.setDarenHomeFansDataExcelDtoList(DarenHomeFansDataMapperImpl.getSingleExcel(uids, map));
            darenDataListDto.setDarenHomeScoreDataExcelDtoList(DarenHomeScoreDataMapperImpl.getSingleExcel(uids, map));
            darenDataListDto.setDarenHomeSellDataExcelDtoList(DarenHomeSellDataMapperImpl.getSingleExcel(uids, map));
            darenDataListDto.setDarenHomeVideoDataExcelDtoList(DarenHomeVideoDataMapperImpl.getSingleExcel(uids, map));
            darenDataListDto.setDarenHomeVideoHistoryExcelDtoList(DarenHomeVideoHistoryMapperImpl.getSingleExcel(uids, map));
        }

        ExcelUtils.getMulSheetExcel(darenDataListDto, basePath);
        return "生成成功";
    }



    @Override
    public String generatorBaseExcel () {
        DarenBaseDo dto = new DarenBaseDo();
        QueryWrapper<DarenBaseDo> wrapper = new QueryWrapper<>(dto);

        // 达人基本信息
        List<DarenBaseDo> darenBaseDos = darenBaseMapper.selectList(wrapper);
        List<DarenBaseSinExcelDto> darenBaseList = JSONArray.parseArray(
                JSONArray.toJSONString(darenBaseDos)
                , DarenBaseSinExcelDto.class);
        DarenDataListDto darenDataListDto = new DarenDataListDto();
        darenDataListDto.setDarenBaseSinExcelDtoList(darenBaseList);

        ExcelUtils.getBaseSheetExcel(darenDataListDto, basePath);
        return "生成成功";
    }

    @Override
    public String generatorProductExcel() {
        QueryWrapper<ProductDataDo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_off_the_shelf", 1);
        wrapper.orderByDesc("commission_effect_start_time");
        // 货盘基本信息
        List<ProductDataDo> productDataList = productDataMapper.selectList(wrapper);
        if (Objects.nonNull(productDataList) && !productDataList.isEmpty()) {
            List<ProductListExcelDto> list = Lists.newArrayList();
            for (ProductDataDo productDataDo : productDataList) {
                ProductListExcelDto dto = new ProductListExcelDto();
                dto.setProductName(productDataDo.getProductName());
                BigDecimal productPrice = new BigDecimal(productDataDo.getProductPrice());
                BigDecimal commissionRate = new BigDecimal(productDataDo.getCommissionRate());
                BigDecimal bd = new BigDecimal(100);
                dto.setProductPrice("¥" + productPrice.divide(bd, 2, RoundingMode.UP));
                dto.setCommissionRate(commissionRate + "%");
                dto.setShopName(productDataDo.getShopName());
                dto.setPromotionUrl(productDataDo.getPromotionUrl());
                String imgPath = basePath + "img//" + productDataDo.getProductId() + ".png";
                String qualityImgPath = basePath + "qualityImg//" + productDataDo.getProductId() + ".jpg";
                File file = new File(imgPath);

                if (!file.exists()) {
                    // 每张图睡1-5秒再下载
                    ThreadUtil.sleep(RandomUtil.randomInt(1, 5), TimeUnit.SECONDS);
                    logger.info("下载图片：{}, 当前时间：{}", imgPath, System.currentTimeMillis());
                    HttpUtil.downloadFile(productDataDo.getProductImg(), imgPath);
                    //压缩比率
                    Img.from(FileUtil.file(imgPath))
                            .setQuality(0.2)
                            .write(FileUtil.file(qualityImgPath));
                }
                dto.setProductFile(new File(qualityImgPath));
                dto.setProductStock(productDataDo.getProductStock());
                list.add(dto);
            }
            ExcelUtils.getProductSheetExcel(list, basePath);
        }

        return "生成成功";
    }

    public static void main(String[] args) {
//        HttpUtil.downloadFile("https://lf3-cm.ecombdstatic.com/obj/ecom-shop-material/RvIZcUaL_m_335b24bbd1677e7ed6aa290f7b040c63_sx_5146633_www3004-3004", "D://douyin//file//img//1.png");
//        Img.from(FileUtil.file("D://douyin//file//img//1.png"))
//                .setQuality(0.6)//压缩比率
//                .write(FileUtil.file("D://douyin//file//img//2.jpg"));
        String imgPath = "D://douyin//file//img//";
        File tarFile = new File(imgPath);
        File[] files = tarFile.listFiles();
        for (File file : files) {
            String qualityImgPath = "D://douyin//file//qualityImg1//";
            String fileName = file.getName();
            String willQualityFileName = fileName.replace("png", "jpg");
            Img.from(FileUtil.file(imgPath + fileName))
                .setQuality(0.2)//压缩比率
                .write(FileUtil.file(qualityImgPath + willQualityFileName));
        }
//        CronUtil.schedule("*/2 * * * * *", new Task() {
//            @Override
//            public void execute() {
//                System.out.println(System.currentTimeMillis());
//            }
//        });
//        ThreadUtil.sleep(3, TimeUnit.SECONDS);
//        System.out.println(System.currentTimeMillis());
//        ThreadUtil.sleep(3, TimeUnit.SECONDS);
//        System.out.println(System.currentTimeMillis());
//        ThreadUtil.sleep(3, TimeUnit.SECONDS);
//        System.out.println(System.currentTimeMillis());
//
//        // 支持秒级别定时任务
//        CronUtil.setMatchSecond(true);
//        CronUtil.start();
    }

}
